var express = require("express");
var router = express.Router();
const { loginService, updateAdminService } = require("../service/adminService");
const { formatResponse, analysisToken } = require("../utils/tool");
const { ValidationError } = require("../utils/errors");

router.post("/login", async function (req, res, next) {
  // 首先应该有验证码的验证
  // console.log(req.body.captcha.toLowerCase());
  // console.log(req.session.captcha);
  // if (req.body.captcha.toLowerCase() !== req.session.captcha.toLowerCase()) {
  //   throw new ValidationError("验证码错误");
  // }

  // 假设验证码通过了
  console.log("============");
  const result = await loginService(req.body);

  if (result.token) {
    res.setHeader("authentication", result.token);
    res.send(formatResponse(0, "登录成功", result.data));
  } else {
    throw new ValidationError("登录失败");
  }

  //
});

// 恢复登录状态
router.get("/whoami", async function (req, res, next) {
  console.log(req.get("Authorization"));
  const token = analysisToken(req.get("Authorization"));
  console.log("token==>", token);
  // 解析token 还原成有用的信息,
  res.send(
    formatResponse(0, "", {
      loginId: token.loginId,
      name: token.name,
      id: token.id,
    })
  );
});

// 修改管理员
router.put("/", async function (req, res, next) {
  let result = await updateAdminService(req.body);
  res.send(result);
});

module.exports = router;
